package cn.qingyun.gis.modules.enterprise.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.qingyun.gis.cache.common.facade.CacheFacade;
import cn.qingyun.gis.common.Result;
import cn.qingyun.gis.exception.CommonException;
import cn.qingyun.gis.modules.init.system.constant.CommonConstant;
import cn.qingyun.gis.modules.init.system.entity.SysUser;
import cn.qingyun.gis.modules.init.system.service.IBaseCommonService;
import cn.qingyun.gis.modules.init.system.service.ISysUserService;
import cn.qingyun.gis.modules.init.system.vo.LoginUser;
import cn.qingyun.gis.sms.constant.AuthConstants;
import cn.qingyun.gis.sms.request.AuthLoginParam;
import cn.qingyun.gis.sms.service.IAuthenticationService;
import cn.qingyun.gis.sms.util.SmsSender;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class IAuthenticationServiceImpl implements IAuthenticationService {
    @Resource
    private ISysUserService iSysUserService;
    @Resource
    private IBaseCommonService iBaseCommonService;

    @Value("${spring.profiles.active:test}")
    private String activeProfile;

    @Override
    public Result<?> adminLogin(AuthLoginParam loginParam) {
        Integer smsCode = loginParam.getSmsCode();
        String phoneNumber = loginParam.getPhoneNumber();

        Object o = CacheFacade.get(String.format(AuthConstants.LOGIN_CODE_FORMATER, phoneNumber));
        if (ObjectUtil.isNull(o)) {
            throw new CommonException("验证码已经失效，请重新发送验证码");
        }
        if (isValid(phoneNumber, smsCode)) {
            // 登录成功，验证权限
            SysUser sysUser = iSysUserService.ensureUserIsValidWithGuestAuth(null, loginParam.getPhoneNumber(), loginParam.getPhoneNumber());
            Result<?> result = Result.okData("登录成功");

            iSysUserService.repackUserInfo(sysUser, (Result<JSONObject>) result);
            LoginUser loginUser = new LoginUser();
            BeanUtils.copyProperties(sysUser, loginUser);
            iBaseCommonService.addLog("用户名: " + sysUser.getUsername() + ",登录成功！", CommonConstant.LOG_TYPE_1, null, loginUser);

            return result;
        } else {
            throw new CommonException("验证码输入错误.");
        }
    }

    private boolean isValid(String phoneNumber, Integer smsCode) {
        if ("prod".equals(activeProfile)) {
            SmsSender.validCode2(phoneNumber, String.valueOf(smsCode));
            return true;
        } else {
            return Objects.nonNull(smsCode) && smsCode.equals(123456);
        }
    }
}
